<?php
/**
 * Description of Cart
 *
 * @author MATT
 */
class Cart {

    private $taxrate;
    private $sessionName;
    private $pcart;

    public function __construct($taxrate = 0, $sessionName = 'PCART'){

        $this->taxrate = $taxrate;
        $this->sessionName = $sessionName;
        $this->pcart = $_SESSION[$sessionName];
    }

    public function  __destruct() {

        $this->pcart['subTotal'] = $subtotal = $this->getSubtotal();
        $this->pcart['shipping'] = $shipping = $this->getShipping();
        $this->pcart['tax'] = $tax = $this->taxrate * $subtotal;
        $this->pcart['grandTotal'] = $subtotal + $shipping + $tax;

        $_SESSION[$this->sessionName] = $this->pcart;
    }

    public function addItem($itemID,
                            $partNumber,
                            $description,
                            $price,
                            $qty){

        $this->pcart['items'][$itemID] = array(
                            'itemID' => $itemID,
                            'partNumber' => $partNumber,
                            'description' => $description,
                            'price' => $price,
                            'qty' => $qty);

    }

    public function updateItem($itemID, $qty){

        if(isset($this->pcart['items'][$itemID])){
            if($qty > 0){
                $this->pcart['items'][$itemID]['qty'] = $qty;
            } else {
                unset($this->pcart['items'][$itemID]);
            }
        }
    }

    public function getSubtotal(){
        $subtotal = 0;
        foreach($this->pcart['items'] as $lineItem){
            $subtotal += $this->pcart['items'] * $this->pcart['qty'];
        }
        return $subtotal;
    }

    public function getShipping(){
        return 0;
    }

    public function getTax(){
        return $this->getSubtotal() * $this->taxrate;
    }

    public function getGrandTotal(){
        return $this->getSubtotal() + $this->getShipping() + $this->getTax();
    }
}
?>
